//
//  SHEmoticonToolbar.swift
//  SHWeibo01
//
//  Created by 卫平玉 on 16/7/29.
//  Copyright © 2016年 卫平玉. All rights reserved.
//

import UIKit

private let tagNum = 2000
enum SHEmoticonToolbarType: Int{
    
    case Default = 0
    
    case Emoji = 1
    
    case Lxh = 2
}

class SHEmoticonToolbar: UIStackView {

    var closure:((type: SHEmoticonToolbarType)->())?
    
    var currentButton: UIButton?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setupCurrentButton(tag: Int){
        
        let button = viewWithTag(tag + tagNum) as! UIButton
        setupCurrentButtons(button)
    }
    
    func setupCurrentButtons(button: UIButton){
        
        if button == currentButton {
            
            return
        }
        
        currentButton?.selected = false
        
        button.selected = true
        
        currentButton = button
    }
    
    //监听方法
    func buttonClick(button: UIButton){
        
        setupCurrentButtons(button)
        closure?(type: SHEmoticonToolbarType(rawValue: button.tag - tagNum)!)
            
    }
    
    
    private func setupUI(){
        
        //设置排列方向
        axis = .Horizontal
        //填充方式
        distribution = .FillEqually
        addChildButtons("left", title: "默认", type: .Default)
        addChildButtons("mid", title: "Emoji", type: .Emoji)
        addChildButtons("right", title: "浪小花", type: .Lxh)
    }
    
    
    func addChildButtons(imgName: String,title: String,type: SHEmoticonToolbarType){
        
        let button = UIButton()
        
        //默认情况选择第一个
        if type == .Default{
            
            setupCurrentButtons(button)
        }
        
        button.tag = type.rawValue + tagNum
        button.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.setTitle(title, forState: UIControlState.Normal)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Selected)
        button.setBackgroundImage(UIImage(named: "compose_emotion_table_\(imgName)_normal"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "compose_emotion_table_\(imgName)_selected"), forState: UIControlState.Selected)
        addArrangedSubview(button)
    }

}
